import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../models/question.dart';
import '../models/answer.dart';
import '../services/api_service.dart';
import 'package:provider/provider.dart';
import '../services/wrong_question_provider.dart';

class QuestionDetailScreen extends StatefulWidget {
  final Question question;
  final bool isFromWrongQuestions; // 新增标记是否来自错题集

  const QuestionDetailScreen({
    Key? key,
    required this.question,
    this.isFromWrongQuestions = false, // 默认为false
  }) : super(key: key);

  @override
  State<QuestionDetailScreen> createState() => _QuestionDetailScreenState();
}

class _QuestionDetailScreenState extends State<QuestionDetailScreen> {
  final ApiService _apiService = ApiService();
  Answer? _answer;
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';
  String? _selectedOption;
  bool _isAnswerSubmitted = false; // 新增：标记用户是否已提交答案
  bool _isInWrongQuestions = false;
  late WrongQuestionProvider _wrongQuestionProvider;

  @override
  void initState() {
    super.initState();
    _loadAnswer();
    _wrongQuestionProvider =
        Provider.of<WrongQuestionProvider>(context, listen: false);
    _checkIfInWrongQuestions();
  }

  Future<void> _loadAnswer() async {
    setState(() {
      _isLoading = true;
      _hasError = false;
    });

    try {
      final answers = await _apiService.getAnswers([widget.question.id]);
      if (answers.isNotEmpty) {
        setState(() {
          _answer = answers.first;
          _isLoading = false;
        });
      } else {
        setState(() {
          _hasError = true;
          _errorMessage = '未找到答案';
          _isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        _hasError = true;
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  // 检查是否在错题集中
  Future<void> _checkIfInWrongQuestions() async {
    final isWrong =
        await _wrongQuestionProvider.isWrongQuestion(widget.question.id);
    if (mounted) {
      setState(() {
        _isInWrongQuestions = isWrong;
      });
    }
  }

  // 添加或移除错题
  Future<void> _toggleWrongQuestion() async {
    if (_isInWrongQuestions) {
      await _wrongQuestionProvider.removeFromWrongQuestions(widget.question.id);
      if (mounted) {
        setState(() {
          _isInWrongQuestions = false;
        });

        // 如果是从错题集进入的，并且移除了错题，则返回
        if (widget.isFromWrongQuestions) {
          Navigator.pop(context);
          return;
        }

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已从错题集中移除')),
        );
      }
    } else {
      await _wrongQuestionProvider.addToWrongQuestions(widget.question);
      if (mounted) {
        setState(() {
          _isInWrongQuestions = true;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('已添加到错题集')),
        );
      }
    }
  }

  // 修改提交答案方法
  void _submitAnswer() {
    if (_selectedOption == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请先选择一个答案')),
      );
      return;
    }

    setState(() {
      _isAnswerSubmitted = true;
    });

    // 答案提交后，检查是否答错
    // 异步处理，避免阻塞UI
    Future.microtask(() async {
      if (_answer != null && _selectedOption != _answer!.answer) {
        print("答案错误，自动添加到错题集");
        await _addToWrongQuestionsIfWrong();
      }
    });
  }

  // 改进添加错题的方法
  Future<void> _addToWrongQuestionsIfWrong() async {
    // 先检查是否已在错题集中
    final isWrong =
        await _wrongQuestionProvider.isWrongQuestion(widget.question.id);
    if (isWrong) {
      print("题目已在错题集中，无需添加");
      setState(() {
        _isInWrongQuestions = true;
      });
      return;
    }

    print("开始添加错题: ID=${widget.question.id}");
    await _wrongQuestionProvider.addToWrongQuestions(widget.question);

    if (mounted) {
      setState(() {
        _isInWrongQuestions = true;
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('已自动添加到错题集'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.question.examTypeText} 题目详情'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: Icon(
              _isInWrongQuestions ? Icons.bookmark : Icons.bookmark_border,
              color: _isInWrongQuestions ? Colors.red : Colors.white,
            ),
            tooltip: _isInWrongQuestions ? '移出错题集' : '加入错题集',
            onPressed: _toggleWrongQuestion,
          ),
        ],
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildQuestionCard(),
            const SizedBox(height: 20),
            // 只有在用户提交答案后才显示答案卡片
            if (_isAnswerSubmitted) _buildAnswerCard(),
            // 如果用户尚未提交答案且已选择答案，显示提交按钮
            if (!_isAnswerSubmitted && _selectedOption != null)
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 16.0),
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: _submitAnswer,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Theme.of(context).colorScheme.primary,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                    ),
                    child: const Text('提交答案', style: TextStyle(fontSize: 16)),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildQuestionCard() {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primary,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    widget.question.questionTypeText,
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                  ),
                ),
                const SizedBox(width: 8),
                Text(
                  '题号: ${widget.question.id}',
                  style: TextStyle(color: Colors.grey[600], fontSize: 12),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Text(
              widget.question.title,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            if (widget.question.titlePic.isNotEmpty) ...[
              const SizedBox(height: 12),
              Center(
                child: CachedNetworkImage(
                  imageUrl: widget.question.titlePic,
                  placeholder: (context, url) =>
                      const CircularProgressIndicator(),
                  errorWidget: (context, url, error) => const Icon(Icons.error),
                  fit: BoxFit.contain,
                  height: 200,
                ),
              ),
            ],
            const SizedBox(height: 16),
            ..._buildOptions(),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildOptions() {
    final options = widget.question.options;
    final optionLabels = ['A', 'B', 'C', 'D'];

    return List.generate(options.length, (index) {
      final option = options[index];
      final isSelected = _selectedOption == optionLabels[index];
      final isCorrect =
          _answer != null && _answer!.answer == optionLabels[index];

      Color? backgroundColor;
      if (_isAnswerSubmitted && _answer != null) {
        if (isCorrect) {
          backgroundColor = Colors.green[100];
        } else if (isSelected && !isCorrect) {
          backgroundColor = Colors.red[100];

          // 如果选错了，检查是否已经触发自动添加到错题集
          if (!_isInWrongQuestions) {
            // 使用Future.microtask确保在构建完成后执行
            Future.microtask(() => _addToWrongQuestionsIfWrong());
          }
        }
      } else if (isSelected) {
        backgroundColor = Colors.blue[100];
      }

      return Padding(
        padding: const EdgeInsets.only(bottom: 8.0),
        child: InkWell(
          onTap: (_isAnswerSubmitted)
              ? null
              : () {
                  setState(() {
                    _selectedOption = optionLabels[index];
                  });
                },
          child: Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: Row(
              children: [
                Text(
                  '${optionLabels[index]}. ',
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                Expanded(
                  child: Text(option.substring(2)), // 去掉选项前的标签 (如 "A、")
                ),
                if (_isAnswerSubmitted && _answer != null && isCorrect)
                  const Icon(Icons.check_circle, color: Colors.green),
                if (_isAnswerSubmitted &&
                    _answer != null &&
                    isSelected &&
                    !isCorrect)
                  const Icon(Icons.cancel, color: Colors.red),
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget _buildAnswerCard() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_hasError) {
      return Center(
        child: Column(
          children: [
            const Icon(Icons.error_outline, size: 48, color: Colors.red),
            const SizedBox(height: 16),
            Text(_errorMessage),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadAnswer,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_answer == null) {
      return const SizedBox.shrink();
    }

    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      color: Colors.green[50],
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '答案解析',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),

                // 如果回答错误，显示添加到错题集按钮
                if (_selectedOption != null &&
                    _answer != null &&
                    _selectedOption != _answer!.answer)
                  TextButton.icon(
                    icon: Icon(
                      _isInWrongQuestions
                          ? Icons.bookmark
                          : Icons.bookmark_add_outlined,
                      color: _isInWrongQuestions ? Colors.red : Colors.blue,
                    ),
                    label: Text(_isInWrongQuestions ? '已加入错题集' : '加入错题集'),
                    onPressed: _toggleWrongQuestion,
                  ),
              ],
            ),
            const Divider(),
            const SizedBox(height: 8),
            Row(
              children: [
                const Text('正确答案: ',
                    style: TextStyle(fontWeight: FontWeight.bold)),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  decoration: BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    _answer!.formattedAnswer,
                    style: const TextStyle(
                        color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            const Text('解析:', style: TextStyle(fontWeight: FontWeight.bold)),
            const SizedBox(height: 8),
            Text(_answer!.explain),
          ],
        ),
      ),
    );
  }
}
